package com.qf.openapi.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.openapi.zuul.feign.CacheFeignClient;
import com.qf.openapi.zuul.utils.ZuulLocalCache;
import com.qf.qfsy.constants.CacheConstants;
import com.qf.qfsy.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * 幂等性过滤器
 */
@Component
@Slf4j
public class IdempotentFilter extends ZuulFilter {

    @Autowired
    CacheFeignClient cacheFeignClient;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 30;
    }

    @Override
    public boolean shouldFilter() {
        // 尊重前面过滤器的判断结果
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean b = currentContext.sendZuulResponse();

        // 还需要查看当前接口的路由信心中是否开启了幂等性的控制
        HttpServletRequest request = currentContext.getRequest();
        String apiname = request.getParameter("apiname");
        String key = CacheConstants.OPENAPI_MAPPING_PREFIX+apiname;
        HashMap routeInfo = (HashMap) ZuulLocalCache.routingCache.get(key);
        String idempotents = (String) routeInfo.get("idempotents");
        boolean flag = idempotents.equals("0"); // 是否配置该接口为幂等接口

        return b&&flag;
    }

    @Override
    public Object run() throws ZuulException {

        //1. 获取请求中的sign
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String sign = request.getParameter("sign");

        //2. 查询缓存中该key是否存在
        String key = "openapi:idempotent:"+sign;

        boolean flag = checkExist(key);

        if (flag){
            // 违反幂等性规则了
            log.info("重复发送请了");
            // 请求就此打住
            currentContext.setSendZuulResponse(false);
            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().println("重复发送请了,请稍后再试");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return null;
        }

        // 把该sign写入redis中,并设置存储时间
        cacheFeignClient.setwithTTl(key,sign,10l);

        return null;
    }

    /**
     * 检查key再缓存中是否存在
     * @param key
     * @return
     */
    private boolean checkExist(String key) {

        R r = cacheFeignClient.get(key);
        Object data = r.getData();
        if (data==null){
            return false;
        }else {
            return true;
        }
    }
}
